package com.oig.sys.base.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.base.dao.ITbUnitConvRateDao;
import com.oig.sys.base.dto.UnitConvRateDto;
import com.oig.sys.base.entity.TbUnitConvRate;
import com.oig.sys.base.service.ITbUnitConvRateService;
import com.oig.sys.base.vo.UnitConvRateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wuxl
 */
@Service
public class TbUnitConvRateServiceImpl implements ITbUnitConvRateService {

	private final ITbUnitConvRateDao tbUnitConvRateDao;

	@Autowired
	public TbUnitConvRateServiceImpl(ITbUnitConvRateDao tbUnitConvRateDao){
		 this.tbUnitConvRateDao = tbUnitConvRateDao;
	}

	@Transactional
	@Override
	public UnitConvRateVo addUnitConvRate(UnitConvRateDto unitConvRateDto) {
		TbUnitConvRate unitConvRate = new TbUnitConvRate();
		BeanUtils.copyProperties(unitConvRateDto,unitConvRate);
		unitConvRate.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbUnitConvRateDao.save(unitConvRate);
		UnitConvRateVo unitConvRateVo = new UnitConvRateVo();
		BeanUtils.copyProperties(unitConvRate,unitConvRateVo);
		return unitConvRateVo;
	}

	@Transactional
	@Override
	public UnitConvRateVo updateUnitConvRate(UnitConvRateDto unitConvRateDto) {
		TbUnitConvRate unitConvRate = this.tbUnitConvRateDao.getTbUnitConvRateById(unitConvRateDto.getId()) ;
		if (unitConvRate==null){
			throw new BadRequestException("error id") ;
		}
		BeanUtils.copyProperties(unitConvRateDto,unitConvRate,"id","status");
		this.tbUnitConvRateDao.save(unitConvRate);
		UnitConvRateVo unitConvRateVo = new UnitConvRateVo();
		BeanUtils.copyProperties(unitConvRate,unitConvRateVo);
		return unitConvRateVo;
	}

	@Transactional
	@Override
	public void delUnitConvRate(Integer id) {
		this.tbUnitConvRateDao.deleteById(id);
	}

	@Override
	public UnitConvRateVo getUnitConvRate(String unitCode, String targetUnitCode) {
		TbUnitConvRate unitConvRate = this.tbUnitConvRateDao.getByUnitCodeAndTargetUnitCode(unitCode,targetUnitCode);
		if (unitConvRate!=null){
			UnitConvRateVo unitConvRateVo = new UnitConvRateVo();
			BeanUtils.copyProperties(unitConvRate,unitConvRateVo);
			return unitConvRateVo;
		}
		return null;
	}
}
